package com.sf.fy.uav.rest;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sf.fy.uav.common.enums.CouponStatusEnum;
import com.sf.fy.uav.common.enums.SettingStatusEnum;
import com.sf.fy.uav.common.request.common.IdRequest;
import com.sf.fy.uav.common.request.operate.CouponRequest;
import com.sf.fy.uav.common.request.operate.QueryCouponRequest;
import com.sf.fy.uav.common.response.operational.CouponResponse;
import com.sf.fy.uav.common.response.operational.EffectiveCouponRsResponse;
import com.sf.fy.uav.common.utils.BeanUtil;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.controller.CouponActivityController;
import com.sf.fy.uav.entity.Coupon;
import com.sf.fy.uav.entity.CouponActivity;
import com.sf.fy.uav.mapper.CouponMapper;
import com.sf.fy.uav.service.CouponService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lixiang
 * @since 2023-09-12
 */
@RestController
@RequestMapping("/sys/coupon")
public class CouponRest {
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private CouponService couponService;

    @Autowired
    private CouponActivityController couponActivityController;
    private static final Byte RADIO_TYPE_TRUE = 0;
    private static final Integer CONT_NUM = 0;
    private static final Byte RADIO_TYPE_FALSE = 1;
    private static final Byte STATUS_NUM = 0;

    private static final Byte STOP_EVENT = 3;


    public List<CouponResponse> getCoupons(QueryCouponRequest queryCouponRequest) {
        return couponService.queryCoupons(queryCouponRequest);
    }

    public Long getTotal(@RequestParam(required = false) String couponName, @RequestParam(required = false) Byte status) {
        return couponService.getTotal(couponName, status);
    }

    public EffectiveCouponRsResponse getEffectiveCoupons(@RequestParam Integer page, @RequestParam Integer size) {
        return couponService.getEffectiveCoupons(page, size);
    }

    public Coupon createCoupon(CouponRequest couponRequest) {
        return couponService.createCoupon(couponRequest);
    }

    public CouponResponse getCouponById(String id) {
        return couponService.queryCouponById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Coupon editCoupon(CouponRequest couponRequest) {
        Coupon coupon = BeanUtil.copyProperties(couponRequest, Coupon.class);
        coupon.setUpdateTime(new Date());
        CouponResponse couponResponse = couponService.queryCouponById(couponRequest.getId());
        if (ObjectUtils.isEmpty(couponResponse)) {
            throw new RuntimeException("无此优惠券!");
        }
        if (!couponRequest.getStatus().equals(couponResponse.getStatus())) {
            throw new RuntimeException("优惠券状态无效!");
        }
        if (StringUtils.isBlank(couponRequest.getId())) {
            throw new RuntimeException("id不能为空!");
        }
        if (ObjectUtils.isEmpty(couponRequest.getStatus())) {
            throw new RuntimeException("状态不能为空!");
        }
        if (CouponStatusEnum.ENDED.getValue().equals(couponRequest.getStatus()) || CouponStatusEnum.LOST_EFFICACY.getValue().equals(couponRequest.getStatus())) {
            throw new RuntimeException("已结束或已失效的优惠券不能编辑!");
        }
        if (CouponStatusEnum.UNDER_WAY.getValue().equals(couponRequest.getStatus())) {
            if (StringUtils.isNotBlank(couponRequest.getCouponName()) || ObjectUtils.isNotEmpty(couponRequest.getCouponType()) || ObjectUtils.isNotEmpty(couponRequest.getDiscount()) || ObjectUtils.isNotEmpty(couponRequest.getThreshold()) || ObjectUtils.isNotEmpty(couponRequest.getThresholdAmount()) || ObjectUtils.isNotEmpty(couponRequest.getDesignatedUserType()) || ObjectUtils.isNotEmpty(couponRequest.getClaimRestriction()) || ObjectUtils.isNotEmpty(couponRequest.getClaimNum()) || ObjectUtils.isNotEmpty(couponRequest.getEffectiveTime()) || ObjectUtils.isNotEmpty(couponRequest.getFailureTime())) {
                throw new RuntimeException("进行中的优惠券只能修改发行量!");
            }
        } else {
            Integer effectiveDays = couponRequest.getEffectiveDays();
            if (ObjectUtils.isEmpty(effectiveDays)) {
                if (ObjectUtils.isEmpty(couponRequest.getEffectiveTime()) || ObjectUtils.isEmpty(couponRequest.getFailureTime())) {
                    throw new RuntimeException("开始时间和结束时间都不能为空!");
                }
                if (!ObjectUtils.isEmpty(couponRequest.getEffectiveTime()) && null != couponRequest.getFailureTime()) {
                    if (couponRequest.getEffectiveTime().equals(couponRequest.getFailureTime()) || couponRequest.getEffectiveTime().getTime() > couponRequest.getFailureTime().getTime()) {
                        throw new RuntimeException("开始时间不能大于等于结束时间!");
                    }
                    if (couponRequest.getEffectiveTime().getTime() < System.currentTimeMillis()) {
                        throw new RuntimeException("开始时间不能小于当前时间!");
                    }
                }
            }
            if (RADIO_TYPE_TRUE.equals(couponRequest.getThreshold())) {
                coupon.setDescription("无门槛,打" + couponRequest.getDiscount() + "折");
                coupon.setThresholdAmount(BigDecimal.ZERO);
            } else if (RADIO_TYPE_FALSE.equals(couponRequest.getThreshold())) {
                coupon.setDescription("满" + couponRequest.getThresholdAmount() + "元," + "打" + couponRequest.getDiscount() + "折");
            }
            if (RADIO_TYPE_TRUE.equals(couponRequest.getClaimRestriction())) {
                coupon.setClaimNum(CONT_NUM);
            }
        }
        if (!ObjectUtils.isEmpty(couponRequest.getEffectiveDays())) {
            coupon.setStatus(CouponStatusEnum.UNDER_WAY.getValue());
        } else {
            coupon.setStatus(couponResponse.getStatus());
        }

        if (STOP_EVENT.equals(couponRequest.getEvent())) {
            coupon.setStatus(STOP_EVENT);
            //下架关联优惠券活动
            couponActivityController.downByCouponIds(Arrays.asList(couponRequest.getId()));
        }
        couponService.updateById(coupon);
        return couponMapper.selectById(coupon.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteCoupon(CouponRequest couponRequest) {
        if (!STATUS_NUM.equals(couponRequest.getStatus())) {
            throw new RuntimeException("只能删除未开始的优惠券!");
        }
        Coupon coupon = BeanUtil.copyProperties(couponRequest, Coupon.class);
        UpdateWrapper<Coupon> updateWrapper = new UpdateWrapper<>();
        coupon.setDel(true);
        coupon.setUpdateTime(new Date());
        updateWrapper.eq("id", couponRequest.getId());
        couponMapper.update(coupon, updateWrapper);
        couponActivityController.downByCouponIds(Collections.singletonList(couponRequest.getId()));
    }

    public Boolean deductionOfInventory(String couponId, Date updateTime, Integer deductionAmount) {
        return couponService.deductionOfInventory(couponId, updateTime, deductionAmount);
    }

    public List<Coupon> getNormalByCouponIds(List<String> couponIds) {
        return couponService.getNormalByCouponIds(couponIds);
    }

    public Integer start(@RequestBody IdRequest idRequest) {
        Coupon coupon = couponMapper.selectById(idRequest.getId());
        if (!org.springframework.util.ObjectUtils.isEmpty(coupon)) {
            if (coupon.getDel() || coupon.getStatus().equals(SettingStatusEnum.OFF.getStatus())) {
                return null;
            }
            if (!org.springframework.util.ObjectUtils.isEmpty(coupon)) {
                Date startTime = coupon.getEffectiveTime();
                Date endTime = coupon.getFailureTime();
                Date date = new Date();
                if (startTime.getTime() > date.getTime()) {
                    //还没开始
                    coupon.setStatus(SettingStatusEnum.NOT_STARTED.getStatus().byteValue());
                } else {
                    if (date.getTime() < endTime.getTime()) {
                        coupon.setStatus(SettingStatusEnum.ON_DISPLAY.getStatus().byteValue());
                    } else {
                        coupon.setStatus(SettingStatusEnum.ENDED.getStatus().byteValue());
                    }
                }
                couponMapper.updateById(coupon);
                return Integer.valueOf(coupon.getStatus());
            }
        }
        return null;
    }

    public Integer end(@RequestBody IdRequest idRequest) {
        Coupon coupon = couponMapper.selectById(idRequest.getId());
        if (ObjectUtils.isEmpty(coupon)) {
            return null;
        }
        if (coupon.getDel() || coupon.getStatus().equals(SettingStatusEnum.OFF.getStatus())) {
            return null;
        }
        if (!org.springframework.util.ObjectUtils.isEmpty(coupon)) {
            Date startTime = coupon.getEffectiveTime();
            Date endTime = coupon.getFailureTime();
            Date date = new Date();
            if (startTime.getTime() > date.getTime()) {
                //还没开始
                coupon.setStatus(SettingStatusEnum.NOT_STARTED.getStatus().byteValue());
            } else {
                if (date.getTime() < endTime.getTime()) {
                    coupon.setStatus(SettingStatusEnum.ON_DISPLAY.getStatus().byteValue());
                } else {
                    coupon.setStatus(SettingStatusEnum.ENDED.getStatus().byteValue());
                }
            }
            couponMapper.updateById(coupon);
            couponActivityController.downByCouponIds(Collections.singletonList(coupon.getId()));
            return Integer.valueOf(coupon.getStatus());
        }
        return null;
    }
}
